<template>
  <div class="home trace">
    <div ref="container" class="container"></div>
    <div
      class="guageContainer"
      v-if="showAniCtr&&currentCtrlCar!=null"
      :style="{'opacity':currentCtrlCar.moving?'1':'0'}"
    >
      <gauge :value="currentCtrlCar.speed"></gauge>
    </div>
    <div
      class="timelinewrapper"
      ref="timelinewrapper"
      v-if="showAniCtr&&currentCtrlCar!=null&&pointsProceed.length>0"
    >
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in pointsProceed"
          :key="index"
          :type="pointsProceedCurrentIndex==index?'success':'info'"
          :timestamp="activity[2]|date"
        >
          <span :style="{color:pointsProceedCurrentIndex==index?'green':''}">{{activity[3]}}</span>
        </el-timeline-item>
      </el-timeline>
    </div>
    <el-button
      type="primary"
      v-if="NODE_ENV=='development'"
      @click="testIfIsOnline"
      style="position:absolute;top:110px;left:10px;margin-left: 0px;"
    >TestIfIsOnline</el-button>
    <el-button
      type="primary"
      v-if="NODE_ENV=='development'"
      @click="rebind"
      style="position:absolute;top:180px;left:10px;"
    >REBIND</el-button>
    <el-button
      type="primary"
      v-if="NODE_ENV=='development'"
      @click="setCarObd"
      style="position:absolute;top:250px;left:10px;margin-left: 0px;"
    >setCarObd</el-button>
    <div class="tools">
      <car-list
        class="deviceList"
        :cars="deviceList"
        ref="carListComponent"
        @carclick="handleListClick"
        @refresh="getDeviceList"
      ></car-list>
      <div class="input-card" :style="{'right':(showAniCtr&&currentCtrlCar!=null)?'0px':'-300px'}">
        <template v-if="currentCtrlCar!=null">
          <h4>{{currentCtrlCar.user_name||currentCtrlCar.plateNumber||currentCtrlCar.name}}</h4>
          <img src="@/assets/close.png" @click="showAniCtr=false;" class="closeIcon" />
          <div class="info2" v-if="carDetailInfo">
            <span>所属单位：</span>
            {{carDetailInfo.companyName}}
          </div>
          <div class="info2">
            <span>车牌号：</span>
            {{currentCtrlCar.plateNumber}}
          </div>
          <div class="info2">
            <span>里程：</span>
            {{currentCtrlCar.statenumber[0]}} km
          </div>
          <div class="info2">
            <span>车速：</span>
            {{currentCtrlCar.su}} km/h
          </div>
          <!-- <div class="info2">
            <span>油量：</span>
            {{currentCtrlCar.statenumber[1]}} L
          </div>
          <div class="info2">
            <span>电量：</span>
            主:{{currentCtrlCar.statenumber[4]}},
            备:{{currentCtrlCar.statenumber[5]}}V,
            {{currentCtrlCar.status[3]=="1"?"充电中":"未充电"}}
          </div>
          <div class="info2">
            <span>车架号：</span>
            {{currentCtrlCar.statenumber[17]}}
          </div>-->
          <div class="info2">
            <span>定位状态：</span>
            {{currentCtrlCar.carOnline==1?'在线':'离线'}}，{{currentCtrlCar.sys_time|date}}
          </div>
          <!-- <div class="info2">
            <span>GPS数：</span>
            {{currentCtrlCar.statenumber[6]}}
          </div>
          <div class="info2">
            <span>信号强度：</span>
            {{currentCtrlCar.statenumber[7]}} asu
          </div>
          <div class="info2">
            <span>高度：</span>
            {{currentCtrlCar.statenumber[14]}} M
          </div>-->
          <div class="info2">
            <span>行车轨迹：</span>
            <el-button type="primary" size="mini" @click="searchPath">搜索</el-button>
          </div>
          <div class="info2 dates">
            <el-date-picker
              v-model="startTime"
              type="date"
              placeholder="开始日期"
              @change="changeStartTime($event)"
            ></el-date-picker>
            <br />
            <el-date-picker
              v-model="endTime"
              type="date"
              placeholder="结束日期"
              @change="changeEndTime($event)"
            ></el-date-picker>
          </div>
          <div class="info2">
            <div class="address">{{startAddress}}</div>
            <div class="address">{{endAddress}}</div>
          </div>
          <el-progress :percentage="currentCtrlCar.percent||0"></el-progress>
          <div class="strokes" v-if="currentCtrlCar.strokes&&currentCtrlCar.strokes.length>0">
            <div class="header row">
              <div>开始时间</div>
              <div>结束时间</div>
              <div>里程</div>
              <div>操作</div>
            </div>
            <template v-for="(item, index) in currentCtrlCar.strokes">
              <div
                class="daywrapper"
                :key="index"
                :style="{'max-height':item[0].height>0?(item[0].height+'px'):'initial'}"
              >
                <div class="divider" @click="item[0].height=(item[0].height==117?0:117)">
                  {{item[0].strokeTime}} ({{item.length}}条)
                  <i
                    class="el-icon-arrow-down"
                    v-if="item[0].height==117&&item.length>3"
                  >查看更多</i>
                  <i class="el-icon-arrow-up" v-if="item[0].height!=117&&item.length>3">收起</i>
                </div>
                <div class="row" v-for="(subItem, index) in item" :key="index">
                  <div>{{subItem.btime}}</div>
                  <div>{{subItem.etime}}</div>
                  <div>{{subItem.distance}}km</div>
                  <div>
                    <el-button
                      size="mini"
                      round
                      @click="getHistoryMByMUtc(currentCtrlCar.sim_id,subItem.BeginTime,subItem.EndTime)"
                    >播放</el-button>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import amapConfig from "@/utils/amapconfig";
import CarList from "./components/CarList/index";
import Gauge from "./components/gauge/index";
import { getCarCodes, setCarObd, listJson } from "@/api/car";
import { mapGetters } from "vuex";
import "./index.scss";
export default {
  components: {
    CarList,
    Gauge,
  },
  computed: {
    ...mapGetters(["selectedComIds"]),
  },
  data() {
    return {
      accountInfo: null,
      map: null, //地图
      deviceList: [], //设备列表
      latestLocations: [], //最新位置
      showAniCtr: false,
      carIconOffline: require("@/assets/carOffline.png"), //地图上车图标
      carIconMoving: require("@/assets/carMoving.png"), //地图上车图标
      carIconOnline: require("@/assets/carOnline.png"), //地图上车图标
      currentCtrlCar: null, //当前控制的车辆
      duration: 300, //轨迹播放每段的时长
      startTime: "",
      endTime: "",
      startAddress: "", //行程开始地址
      endAddress: "", //行程结束地址
      MapType: "GAODE", //坐标系 请求接口时参数
      loading: null,
      carcodes: [], //本单位车辆
      pointsProceed: [], //正在播放的行程的抽稀后的点和对应的时间以及时间点对应的具体地址
      pointsProceedCurrentIndex: 0, //当前播放的行程的当前时间点的index，用于显示现在行驶到哪里哪条路了
      clusterDatas: [], //聚合图层的参数 后面获取车辆最新位置后需要进行更新
      carDetailInfo: null, //当前车辆的详情，从自己服务器获取的数据，目前用来显示车辆所属单位
    };
  },
  watch: {
    pointsProceedCurrentIndex() {
      if (this.$refs.timelinewrapper) {
        this.$refs.timelinewrapper.scrollTop =
          (this.pointsProceedCurrentIndex > 3
            ? this.pointsProceedCurrentIndex - 3
            : 0) * 64;
      }
    },
    async selectedComIds() {
      await this.getCarCodes();
      this.getDeviceList();
    },
  },
  created() {
    this.getCarCodes();
    this.loadMap();
    this.$store.dispatch("app/closeSideBar", { withoutAnimation: true });
    this.loading = this.$loading({
      lock: true,
      text: "努力加载中",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    window.intervalGetUserAndGpsInfoByIDsUtc = setInterval(() => {
      //this.getUserAndGpsInfoByIDsUtc();
      this.getDeviceListByCustomId();
    }, 3000);
  },
  beforeDestroy() {
    window.clearInterval(window.intervalGetUserAndGpsInfoByIDsUtc);
  },
  methods: {
    //先获取本单位车辆列表  然后将obd服务器返回的列表进行过滤
    getCarCodes() {
      return new Promise(async (resolve, reject) => {
        try {
          let data = await getCarCodes({
            comIds: this.selectedComIds.join(","),
          });
          if (data && data.error == 0 && data.codes) {
            this.carcodes.splice(
              0,
              this.carcodes.length,
              ...data.codes.split(",")
            );
          }
          resolve();
        } catch (error) {
          reject(error);
        }
      });
    },
    //加载地图
    loadMap() {
      AMapLoader.load(amapConfig)
        .then((AMap) => {
          window.AMap = AMap;
          this.loadAmapPlugin();
        })
        .catch((e) => {
          console.log(e);
        });
    },
    //检测刚安装的obd是否在线 或者是否已经被绑定等异常情况
    async testIfIsOnline() {
      let data = `600676    600676`
        .split("\n")
        .map((e) => {
          return e.replace(/\s+/g, ",");
        })
        .map(function (e) {
          return {
            macid: e.split(",")[0],
            FullName: e.split(",")[1],
          };
        });
      console.log(JSON.stringify(data));
      let hasError = false;
      data = data.map((d) => {
        let matchCount = 0;
        this.deviceList.forEach((e) => {
          if (e.macid.endsWith(d.macid)) {
            if (e.fullName.startsWith("辽") || e.fullName.length < 10) {
              console.log("已经被绑定", e);
            }
            matchCount++;
            d.macid = e.macid;
            if (e.carOffline == 0) {
              console.log("在线");
            } else {
              console.log(e.macid + ":" + "离线");
            }
          }
        });
        if (matchCount > 1) {
          hasError = true;
          console.log(d);
          throw Error("重复匹配到macid");
        }
        if (matchCount == 0) {
          hasError = true;
          console.log(d);
          throw Error("没有匹配到macid");
        }
        return d;
      });
      if (hasError) {
        return;
      } else {
        window.obdData = data;
      }
    },
    //重新绑定obd设备 用于重命名obd设备为正确的车牌号 仅开发时使用
    async rebind() {
      let data = window.obdData || [];
      let hasError = false;
      data = data.map((d) => {
        let matchCount = 0;
        this.deviceList.forEach((e) => {
          if (e.macid.endsWith(d.macid)) {
            matchCount++;
            d.macid = e.macid;
          }
        });
        if (matchCount > 1) {
          hasError = true;
          console.log(d);
          throw Error("重复匹配到macid");
        }
        if (matchCount == 0) {
          hasError = true;
          console.log(d);
          throw Error("没有匹配到macid");
        }
        console.log("匹配正常");
        return d;
      });
      if (hasError) {
        return;
      }
      console.log("匹配结束", data);
      for (let i = 0; i < data.length; i++) {
        let unbindingRes = await this.unbinding(data[i].macid);
        if (unbindingRes && unbindingRes["success"] == "true") {
          let ActiveAndAddDeviceRes = await this.ActiveAndAddDevice(
            data[i].macid,
            data[i].FullName
          );
          if (
            ActiveAndAddDeviceRes &&
            ActiveAndAddDeviceRes["success"] == "true"
          ) {
            console.log("绑定成功");
          } else {
            console.log("重绑定失败", data[i], ActiveAndAddDeviceRes);
          }
        } else {
          console.log("解绑失败", data[i], unbindingRes);
        }
      }
    },
    //解绑obd
    async unbinding(macid) {
      let url = `${this.obd_server}/GetDateServices.asmx/GetDate?method=unbundlingDevice&mds=${this.accountInfo.mds}&macid=${macid}&login_id=${this.accountInfo.id}`;
      let data = await this.jsonp(url);
      return data;
    },
    //重新绑定obd
    async ActiveAndAddDevice(macid, FullName) {
      let url = `${this.obd_server}/GetDateServices.asmx/GetDate?method=ActiveAndAddDevice&login_id=${this.accountInfo.id}&mds=${this.accountInfo.mds}&FullName=${FullName}&Macid=${macid}&Platenumber=${FullName}`;
      let data = await this.jsonp(url);
      return data;
    },
    //定时刷新当前查看的车辆的位置
    async getUserAndGpsInfoByIDsUtc() {
      if (this.currentCtrlCar != null) {
        let url = `${this.obd_server}/GetDateServices.asmx/GetDate?mapType=${this.MapType}&mds=${this.accountInfo.mds}&method=getUserAndGpsInfoByIDsUtc&option=cn&user_id=${this.currentCtrlCar.user_id}`;
        let data = await this.jsonp(url);
        if (data && data.records && data.records.length > 0) {
          data = data.records[0];
          if (data[1] == this.currentCtrlCar.plateNumber) {
            let index = this.latestLocations.findIndex(
              (e) => e.plateNumber == this.currentCtrlCar.plateNumber
            );
            if (index != -1 && this.latestLocations[index].clusterMarker) {
              this.latestLocations[index].clusterMarker.setPosition([
                data[2],
                data[3],
              ]);
            }
            let clusIndex = this.clusterDatas.findIndex(
              (e) =>
                e.latestLocation.plateNumber == this.currentCtrlCar.plateNumber
            );
            if (clusIndex != -1) {
              // this.clusterDatas[clusIndex].lnglat[0]=data[2];
              // this.clusterDatas[clusIndex].lnglat[1]=data[3];
              this.clusterDatas[clusIndex].lnglat = [data[2], data[3]];
              window.cluster.setData(this.clusterDatas);
            }
          }
        }
      }
    },
    // JSAPI2.0 使用覆盖物动画必须先加载动画插件
    loadAmapPlugin() {
      window.AMap.plugin(
        [
          "AMap.MoveAnimation",
          "AMap.ControlBar",
          "AMap.ToolBar",
          "AMap.MarkerCluster",
        ],
        () => {
          //生成amap地图对象
          //盘锦121.992574,41.26919
          //沈阳123.47397,41.693096
          let map = new window.AMap.Map(this.$refs.container, {
            resizeEnable: true,
            center: [121.992574, 41.26919],
            zoom: 8,
            viewMode: "3D",
          });
          window.geocoder = new window.AMap.Geocoder({
            extensions: "all",
            radius: 1000, //范围，默认：500
          });
          window.map = map;
          //3d控制器
          let controlBar = new window.AMap.ControlBar({
            position: {
              right: "10px",
              top: "10px",
            },
          });
          controlBar.addTo(map);
          //缩放工具
          window.map.addControl(new window.AMap.ToolBar());
          this.login();
        }
      );
    },
    //登录服务器
    async login() {
      let url = `${this.obd_server}/GetDateServices.asmx/loginSystem`;
      let params = {
        LoginName: "obdapitest",
        //LoginName: "fangbing",
        LoginPassword: "123456",
        LoginType: "ENTERPRISE",
        language: "cn",
        ISMD5: "0",
        apply: "APP",
        loginUrl: "http://vipapi.18gps.net1",
      };
      let data = await this.jsonp(url, params);
      this.accountInfo = data;
      this.getDeviceList();
    },
    //获取设备列表
    async getDeviceList() {
      let url = `${this.obd_server}/GetDateServices.asmx/GetDate?mapType=${this.MapType}&method=getDeviceList&mds=${this.accountInfo.mds}`;
      let data = await this.jsonp(url);
      let maxOfflineTimeInMin =
        this.NODE_ENV == "development" ? 60 * 24 * 2 : 25;
      // maxOfflineTimeInMin = 25;
      //单位管理员显示自己单位的车辆 总管理员显示全部或者根据勾选的单位显示
      data.rows = this.filterCompanyDeviceList(data.rows);
      data.rows.forEach((e) => {
        if (!e.server_time) {
          e.carOffline = 1;
        } else if (
          (e.server_time - e.gpstime) / 1000 / 60 >
          maxOfflineTimeInMin
        ) {
          e.carOffline = 1;
        } else {
          e.carOffline = 0;
        }
        if (e.carOffline == 1 && e.offline == "0") {
          e.carOffline = 1;
        }
      });
      data.rows = data.rows.sort((a, b) => {
        return a.carOffline - b.carOffline;
      });
      this.deviceList.splice(0, this.deviceList.length, ...data.rows);
      this.getDeviceListByCustomId();
    },
    //更新数据库车辆obd的macid
    setCarObd() {
      if (this.$store.getters.userInfo.usertype == 1) {
        for (let i = 0; i < this.deviceList.length; i++) {
          if (this.deviceList[i].platenumber) {
            setTimeout(() => {
              setCarObd({
                carcode: this.deviceList[i].platenumber,
                obd: this.deviceList[i].macid,
              });
            }, 100 * i);
          }
        }
      } else {
        this.$message({
          message: "当前登录非管理员账号，无法更新",
          type: "error",
        });
      }
    },
    //obd服务器返回了全部obd设备 需要根据单位的obd设备进行过滤显示
    filterCompanyDeviceList(deviceList) {
      //如果总管理员没有勾选任何单位，那么接口返回all，此时显示全部，否则进行筛选
      if (this.carcodes && this.carcodes[0] == "all") {
        return deviceList;
      }
      //过滤显示
      deviceList = deviceList.filter((e) => {
        return this.carcodes.indexOf(e.platenumber) >= 0;
      });
      //有的车辆在数据库中有，但是在厂家服务器没有，此时需要添加到列表中显示
      let onBindObdCars = [];
      this.carcodes.forEach((carcode) => {
        let index = deviceList.findIndex((e) => e.platenumber == carcode);
        if (index == -1) {
          onBindObdCars.push(carcode);
        }
      });
      onBindObdCars = onBindObdCars.map((e) => {
        return {
          fullName: e,
          platenumber: e,
        };
      });
      deviceList.push(...onBindObdCars);
      return deviceList;
    },
    changeStartTime(ev) {},
    changeEndTime(ev) {},
    searchPath() {
      if (this.startTime && this.endTime) {
        this.getStrokeV3(this.currentCtrlCar.sim_id, [
          Number.parseInt(this.startTime.getTime()) - 1000,
          Number.parseInt(this.endTime.getTime()) + 1000,
        ]);
      } else {
        this.$message("请选择日期");
      }
    },
    //获取行程
    async getStrokeV3(macid, ev) {
      this.removeBefore();
      this.pointsProceed.splice(0, this.pointsProceed.length);
      let startTime, endTime;
      if (ev) {
        startTime = new Date(ev[0]).getTime();
        endTime = new Date(ev[1]).getTime();
      } else {
        let d = new Date();
        endTime = d.getTime();
        d.setMonth(d.getMonth() - 1);
        startTime = d.getTime();
      }
      this.showAniCtr = true;
      let index = this.latestLocations.findIndex((e) => e.sim_id == macid);
      if (index == -1) {
        console.error("findindex==-1,macid=" + macid);
        return;
      }
      let carPosition = new window.AMap.LngLat(
        this.latestLocations[index].jingdu,
        this.latestLocations[index].weidu
      );
      window.map.setZoomAndCenter(18, carPosition);
      let url = `${this.obd_server}/GetDateServices.asmx/GetDate?mapType=${this.MapType}&method=getStrokeV3&macid=${macid}&beginTime=${startTime}&endTime=${endTime}&mds=${this.accountInfo.mds}`;
      let data = await this.jsonp(url);
      if (data["success"] != "true") {
        this.$message("获取行程失败");
      }
      if (data["rows"].length == 0) {
        this.$message("没有行程数据");
      }
      let obj = {};
      data["rows"].forEach((e) => {
        if (!obj[e.strokeTime]) {
          obj[e.strokeTime] = [];
        }
        e.height = 117;
        obj[e.strokeTime].push(e);
      });
      this.latestLocations[index].strokes.splice(
        0,
        this.latestLocations[index].strokes.length
      );
      for (let key in obj) {
        this.latestLocations[index].strokes.push(obj[key]);
      }
      this.currentCtrlCar = this.latestLocations[index];
      // console.log(this.currentCtrlCar);

      // if (this.$route.params.startTime&&this.$route.params.endTime) {
      //   this.getHistoryMByMUtc(
      //     macid,
      //     this.$route.params.startTime,
      //     this.$route.params.endTime
      //   );
      // }
    },
    //批量获取最新位置
    async getDeviceListByCustomId() {
      if (!this.accountInfo) return;
      let url = `${this.obd_server}/GetDateServices.asmx/GetDate?mapType=${this.MapType}&method=getDeviceListByCustomId&mds=${this.accountInfo.mds}&id=${this.accountInfo.id}&mapTyp=GAODE`;
      let data = await this.jsonp(url);
      let keys = data.data[0].key;
      //对返回对数据进行处理
      //处理后格式：
      // {
      //   sys_time: 1588648032000,
      //   user_name: "我的爱车",
      //   jingdu: 113.93119241,
      //   weidu: 22.52883452,
      //   ljingdu: 113.93119241,
      //   lweidu: 22.52883452,
      //   datetime: 1588648020000,
      //   heart_time: 1588908415328,
      //   su: "0",
      //   status: "001000100",
      //   hangxiang: 80,
      //   sim_id: "025194201502",
      //   user_id: "bfbf0e968ee5453ea2f4370cfc77056a",
      //   sale_type: 0,
      //   iconType: "22",
      //   server_time: 1588908442425,
      //   product_type: "B25",
      //   expire_date: 1588896000000,
      //   group_id: "0",
      //   statenumber:
      //     "583.37,0,0,,100,12.53,0,23,0,1,0,0,0,0,0,0,0,WBA7T0108LGJ09142,Parking",
      //   electric: 100,
      //   describe: "ICCID:89860405191990132239",
      //   sim: "",
      //   precision: 10,
      //   isFollow: "0",
      //   plateNumber: "1224213213",
      //   auth: "0",
      //   authList: ""
      // };

      let latestLocations = data.data[0].records.map((record) => {
        let obj = {
          strokes: [],
          clusterMarker: null,
        };
        for (let key in keys) {
          obj[key] = record[keys[key]];
        }
        obj.carMarker = null;
        if (obj.status && obj.status.length >= 8) {
          obj.status = obj.status.split("");
        }
        obj.statenumber = obj.statenumber.split(",");
        if (Number.parseInt(obj.statenumber[4]) > 100) {
          obj.statenumber[4] = Number.parseInt(obj.statenumber[4]) - 100 + "V";
        } else {
          obj.statenumber[4] = obj.statenumber[4] + "%";
        }
        if (
          this.currentCtrlCar != null &&
          this.currentCtrlCar.sim_id == obj.sim_id
        ) {
          this.currentCtrlCar.jingdu = obj.jingdu;
          this.currentCtrlCar.weidu = obj.weidu;
          this.currentCtrlCar.su = obj.su;
          this.currentCtrlCar.sys_time = obj.sys_time;
          for (let key in this.currentCtrlCar) {
            if (typeof obj[key] === "undefined" || obj[key] == null) {
              obj[key] = this.currentCtrlCar[key];
            }
          }
        }
        obj.percent = 0; //轨迹播放进度
        obj.moving = false; //是否正在播放轨迹
        let deviceListIndex =
          this.deviceList.findIndex((e) => e.macid == obj.sim_id) || 0;
        if (deviceListIndex >= 0) {
          obj.currentSpeed = Number.parseInt(
            this.deviceList[deviceListIndex].speed
          );
        }
        if (
          (Number.parseInt(obj.server_time) - Number.parseInt(obj.sys_time)) /
            1000 /
            60 >
          25
        ) {
          obj.carOnline = 0;
        } else {
          obj.carOnline = 1;
        }
        return obj;
      });
      if (this.carcodes && this.carcodes[0] != "all") {
        latestLocations = latestLocations.filter((e) => {
          return this.carcodes.indexOf(e.plateNumber) >= 0;
        });
      }
      this.latestLocations.splice(
        0,
        this.latestLocations.length,
        ...latestLocations
      );
      this.showCars();
      this.showTargetCar();
    },
    //如果url传递来参数那么查询指定车辆和时间段的轨迹
    showTargetCar() {
      if (this.$route.params.macid || this.$route.params.carcode) {
        let macid;
        if (this.$route.params.macid) {
          macid = this.$route.params.macid;
        } else {
          let index = this.deviceList.findIndex(
            (e) => e.platenumber == this.$route.params.carcode
          );
          if (index != -1) {
            macid = this.deviceList[index].macid;
          }
        }
        //删掉传来的参数 避免setinterval时候重复调用本方法
        delete this.$route.params.macid;
        delete this.$route.params.carcode;
        if (!macid) {
          this.$message({
            message: "没有查询到对应到车辆",
            type: "error",
          });
          return;
        }
        //因API的原因需要适当增大查询范围才能查到特定时间段内的行程
        if (this.$route.params.startTime && this.$route.params.endTime) {
          this.getStrokeV3(macid, [
            Number.parseInt(this.$route.params.startTime) - 1000,
            Number.parseInt(this.$route.params.endTime) + 1000,
          ]);
        } else {
          this.getStrokeV3(macid);
        }
      }
    },
    //经纬度转地址
    async regeoCode(start, end) {
      window.geocoder.getAddress(start, (status, result) => {
        if (status === "complete" && result.regeocode) {
          let addressComponent = result.regeocode.addressComponent;
          this.startAddress =
            "起始地：" +
            addressComponent.city +
            addressComponent.district +
            addressComponent.street +
            addressComponent.streetNumber;
          console.log(addressComponent);
        } else {
          console.log("根据经纬度查询地址失败");
        }
      });
      window.geocoder.getAddress(end, (status, result) => {
        if (status === "complete" && result.regeocode) {
          let addressComponent = result.regeocode.addressComponent;
          this.endAddress =
            "目的地：" +
            addressComponent.city +
            addressComponent.district +
            addressComponent.street +
            addressComponent.streetNumber;
        } else {
          console.log("根据经纬度查询地址失败");
        }
      });
    },
    //批量获取最新位置
    async getHistoryMByMUtc(macid, from, to) {
      this.endAddress = "";
      this.startAddress = "";
      let ua = navigator.userAgent;
      if (ua.indexOf("QQ") >= 0 && ua.indexOf("iPhone") >= 0) {
        this.$alert(
          'iPhone QQ内置浏览器不支持查看轨迹，请点击右上角选择"用Safari打开"'
        );
        return;
      }
      if (this.latestLocations.findIndex((e) => e.sim_id == macid) == -1) {
        console.error("findindex==-1,macid=" + macid);
        return;
      }
      console.log("macid:", macid);
      let loading = this.$loading({ text: "正在获取轨迹数据..." });
      let url = `${this.obd_server}/GetDateServices.asmx/GetDate?mapType=${this.MapType}&method=getHistoryMByMUtc&mds=${this.accountInfo.mds}&playLBS=true&macid=${macid}&from=${from}&to=${to}`;
      let data = await this.jsonp(url);
      loading.close();
      let points = []; //轨迹经纬度
      let speeds = []; //速度
      data.split(";").forEach((e) => {
        let lan = e.split(",")[0];
        let lat = e.split(",")[1];
        let time = e.split(",")[2];
        lan = Number.parseFloat(lan);
        lat = Number.parseFloat(lat);
        if (lan > 0 && lat > 0) {
          points.push([lan, lat, time]);
        }
        speeds.push(Number.parseInt(e.split(",")[3]) || 0);
      });
      if (points.length == 0) {
        this.$message("轨迹数量为0，无法绘制");
      } else {
        this.drawPath(points, macid, speeds);
        if (points.length > 1) {
          this.regeoCode(points[0], points[points.length - 1]);
        }
        let pointsProceed = [];
        for (let i = 0; i < points.length; i++) {
          pointsProceed.push([
            points[i][0],
            points[i][1],
            Number.parseInt(points[i][2]),
          ]);
          i += 20;
        }
        this.pointsProceedCurrentIndex = 0;
        window.geocoder.getAddress(
          JSON.parse(JSON.stringify(pointsProceed)),
          (status, result) => {
            if (status === "complete" && result.regeocodes) {
              result.regeocodes.forEach((element, index) => {
                let addressComponent = element.addressComponent;
                let startAddress =
                  addressComponent.city +
                  addressComponent.district +
                  addressComponent.township +
                  (element.roads[0] ? element.roads[0].name : "");
                pointsProceed[index][3] = startAddress;
              });
              this.pointsProceed.splice(
                0,
                this.pointsProceed.length,
                ...pointsProceed
              );
              console.log(pointsProceed);
            } else {
              console.log("根据经纬度查询地址失败");
            }
          }
        );
      }
    },
    //是否移动端
    isMobile() {
      let ua = navigator.userAgent;
      let ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
        isIphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
        isAndroid = ua.match(/(Android)\s+([\d.]+)/),
        isMobile = isIphone || isAndroid;
      if (isMobile) {
        return true;
      } else {
        return false;
      }
    },
    //处理车辆列表组件点击事件
    handleListClick(carInfo) {
      console.log(carInfo);
      // /  this.getUserAndGpsInfoByIDsUtc(carInfo.macid);
      this.getStrokeV3(carInfo.macid);
      this.carListJson(carInfo);
    },
    //点击车辆后获取车辆详情，以便显示单位信息
    async carListJson(carInfo) {
      console.log(carInfo);
      this.carDetailInfo = null;
      let r = await listJson({
        companyName: carInfo.plateNumber || carInfo.platenumber,
      });
      if (r && r.error == 0 && r.data && r.data.length > 0) {
        this.carDetailInfo = r.data[0];
      }
    },
    //在地图上显示车辆
    showCars() {
      // labelMarker在2.0版本有bug，移动端不可点击，改为marker+text展示
      if (window.cluster) {
        window.cluster.setMap(null);
      }
      this.loading.close();
      this.clusterDatas.splice(0, this.clusterDatas.length);
      for (let i = 0; i < this.latestLocations.length; i++) {
        if (Number.parseFloat(this.latestLocations[i].jingdu) <= 0) {
          continue;
        }
        let lnglat = new window.AMap.LngLat(
          this.latestLocations[i].jingdu,
          this.latestLocations[i].weidu
        );
        this.clusterDatas.push({
          lnglat: [
            this.latestLocations[i].jingdu,
            this.latestLocations[i].weidu,
          ],
          latestLocation: this.latestLocations[i],
        });
        let icon;
        if (this.latestLocations[i].carOnline == 1) {
          if (this.latestLocations[i].currentSpeed > 0) {
            icon = this.carIconMoving;
          } else {
            icon = this.carIconOnline;
          }
        } else {
          icon = this.carIconOffline;
        }
        this.latestLocations[i].icon = icon;
        this.latestLocations[i].vuethis = this;
      }
      // if (
      //   this.currentCtrlCar &&
      //   !this.currentCtrlCar.moving &&
      //   this.showAniCtr
      // ) {
      //   window.map.setCenter([
      //     this.currentCtrlCar.jingdu,
      //     this.currentCtrlCar.weidu
      //   ]);
      // }
      window.cluster = new window.AMap.MarkerCluster(
        window.map,
        this.clusterDatas,
        {
          renderMarker: function (context) {
            let data = context.data[0];
            var content = `<div>
            <img src="${data.latestLocation.icon}"/>
            <span style="border:solid 1px #999;background:white;white-space:nowrap;padding:0px 4px;position:relative;left:-20px;font-size:10px;">${
              data.latestLocation.user_name || data.latestLocation.plateNumber
            }</span>
            </div>`;
            var offset = new AMap.Pixel(-9, -9);
            context.marker.setContent(content);
            context.marker.setAngle(data.latestLocation.hangxiang);
            context.marker.setExtData(data.latestLocation);
            data.latestLocation.clusterMarker = context.marker;
            context.marker.on("click", function () {
              //this指向当前marker
              //vuethis.getStrokeV3(this._opts.sim_id);
              let extraData = this.getExtData();
              extraData.vuethis.getStrokeV3(extraData.sim_id);
              extraData.vuethis.carListJson(extraData);
            });
          },
        }
      );
    },
    //移除之前车辆的地图图层
    removeBefore() {
      if (
        this.currentCtrlCar &&
        this.currentCtrlCar.carMarker &&
        this.currentCtrlCar.moving
      ) {
        this.currentCtrlCar.carMarker.stopMove();
        this.currentCtrlCar.carMarker.remove();
      }
      if (window.polyline) {
        window.map.remove(window.polyline);
      }
      if (window.passedPolyline) {
        window.map.remove(window.passedPolyline);
      }
    },
    //绘制轨迹
    /**
     * points 经纬度轨迹
     * macid 车辆obd id
     * speeds 车速
     */
    drawPath(points, macid, speeds) {
      window.clearTimeout(window.timer);
      this.removeBefore();
      //如果之前的车辆在播放轨迹那么停掉
      //展示动画时候关闭页面对话框
      //this.$refs.carListComponent.closeDialogAndList();
      //对应的最新位置对象
      console.log(this.latestLocations.findIndex((e) => e.sim_id == macid));
      let latestLocationObj = this.latestLocations[
        this.latestLocations.findIndex((e) => e.sim_id == macid)
      ];
      latestLocationObj.speeds = speeds;
      latestLocationObj.speed = 0;

      let icon;
      if (latestLocationObj.carOnline == 1) {
        if (latestLocationObj.currentSpeed > 0) {
          icon = this.carIconMoving;
        } else {
          icon = this.carIconOnline;
        }
      } else {
        icon = this.carIconOffline;
      }
      let marker = new window.AMap.Marker({
        position: points[0],
        icon: icon,
        sim_id: latestLocationObj.sim_id,
        anchor: "center",
      });
      window.map.add(marker);
      if (latestLocationObj.carMarker) {
        latestLocationObj.carMarker.remove();
      }
      latestLocationObj.carMarker = marker;
      latestLocationObj.points = points;
      // 绘制轨迹
      let polyline = new window.AMap.Polyline({
        map: window.map,
        path: points,
        showDir: true,
        strokeColor: "#28F", //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 10, //线宽
        // strokeStyle: "solid"  //线样式
      });
      window.polyline = polyline;
      //已移动过的轨迹
      let passedPolyline = new window.AMap.Polyline({
        map: window.map,
        strokeColor: "#AF5", //线颜色
        strokeWeight: 10, //线宽
      });
      window.passedPolyline = passedPolyline;
      latestLocationObj.carMarker.passedPolyline = passedPolyline;
      latestLocationObj.carMarker.latestLocationObj = latestLocationObj;
      //清除之前的回调事件
      window.points = points;
      window.that = this;
      latestLocationObj.carMarker.on("moving", function (e) {
        if (e.passedPath.length % 20 == 0) {
          //pointsProceed
          let maxIndex = window.that.pointsProceed.length - 1;
          let currentIndex = e.passedPath.length / 20;
          window.that.pointsProceedCurrentIndex =
            currentIndex > maxIndex ? maxIndex : currentIndex;
        }
        this.passedPolyline.setPath(e.passedPath);
        //记录当前车速
        this.latestLocationObj.speed = this.latestLocationObj.speeds[
          e.passedPath.length - 1
        ];
        //计数每次回调 每x次设置一次地图视角  避免太频繁造成3d眩晕
        e.target.rotateCount = e.target.rotateCount ? e.target.rotateCount : 0;
        if (e.target.rotateCount % 100 == 0) {
          window.map.setRotation(e.target.lastAngle);
        }
        //获取地图显示范围并缩小一定距离，车子不在范围内就移动地图中心
        let mapBounds = window.map.getBounds();
        let carPosition = e.target.getPosition();
        let southWest = mapBounds.getSouthWest();
        let northEast = mapBounds.getNorthEast();
        let offset = 200;
        southWest = southWest.offset(offset, offset);
        northEast = northEast.offset(-offset, -offset);
        let smallerMapBounds = new window.AMap.Bounds(southWest, northEast);
        if (
          !smallerMapBounds.contains(carPosition) ||
          e.target.rotateCount == 0
        ) {
          window.map.setCenter(e.target.getPosition(), false, 100);
        }
        e.target.rotateCount++;
        //完成度百分比
        let percent =
          (this.latestLocationObj.points.indexOf(e.passedPos) + 1) /
          this.latestLocationObj.points.length;
        percent = percent * 100;
        if (e.passedPath.length == this.latestLocationObj.points.length) {
          percent = 100;
          this.latestLocationObj.moving = false;
          window.map.setFitView(this.passedPolyline, false);
        }
        percent = Number.parseInt(percent);
        this.latestLocationObj.percent = percent;
      });

      window.map.setRotation(0);
      window.map.setFitView(polyline, true);

      this.currentCtrlCar = latestLocationObj;
      window.map.setPitch(50);
      window.timer = setTimeout(() => {
        console.log(this.currentCtrlCar);
        window.map.setZoom(18);
        this.currentCtrlCar.moving = true;
        //设置3d展示
        this.currentCtrlCar.carMarker.moveAlong(this.currentCtrlCar.points, {
          // 每一段的时长
          duration: this.duration,
          // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
          autoRotation: true,
        });
      }, 2500);
    },
  },
};
</script>
<style lang="scss">
</style>
<style lang="scss" scoped>
</style>